'use client'

import { useEffect, useState } from 'react'
import { User, UserRole } from '@/types'
import { UserForm } from '@/components/users/user-form'

export default function UsersPage() {
  const [users, setUsers] = useState<User[]>([])
  const [editingUser, setEditingUser] = useState<User | null>(null)

  useEffect(() => {
    async function fetchUsers() {
      try {
        const response = await fetch('/api/users')
        if (!response.ok) {
          throw new Error('网络错误')
        }
        const data = await response.json()
        if (Array.isArray(data)) {
          setUsers(data)
        } else {
          console.error('返回的数据不是数组:', data)
        }
      } catch (error) {
        console.error('获取用户数据失败:', error)
      }
    }
    fetchUsers()
  }, [])

  const handleEdit = (user: User) => {
    setEditingUser(user)
  }

  const handleDelete = async (id: number) => {
    const response = await fetch(`/api/users/${id}`, { method: 'DELETE' })
    if (response.ok) {
      setUsers(users.filter(user => user.id !== id))
    } else {
      console.error('删除用户失败')
    }
  }

  const handleSave = (updatedUsers: User[]) => {
    setUsers(updatedUsers)
  }

  // 角色映射
  const roleMap: { [key in UserRole]: string } = {
    [UserRole.ADMIN]: '超级管理员',
    [UserRole.MANAGER]: '经理',
    [UserRole.STAFF]: '员工',
  }

  return (
    <div className="space-y-4 p-8 bg-gray-50">
      <h1 className="text-2xl font-bold text-gray-800">用户管理</h1>
      <UserForm user={editingUser} onClose={() => setEditingUser(null)} onSave={handleSave} />
      <table className="min-w-full mt-4 border-collapse border border-gray-300">
        <thead>
          <tr>
            <th className="border border-gray-300 p-2 text-left text-gray-800">用户名</th>
            <th className="border border-gray-300 p-2 text-left text-gray-800">角色</th>
            <th className="border border-gray-300 p-2 text-left text-gray-800">操作</th>
          </tr>
        </thead>
        <tbody>
          {users.map(user => (
            <tr key={user.id} className="hover:bg-gray-100">
              <td className="border border-gray-300 p-2 text-gray-800">{user.username}</td>
              <td className="border border-gray-300 p-2 text-gray-800">{roleMap[user.role]}</td>
              <td className="border border-gray-300 p-2">
                <button onClick={() => handleEdit(user)} className="text-blue-600 hover:underline" disabled={user.role === UserRole.ADMIN}>
                  编辑
                </button>
                {user.role !== UserRole.ADMIN && (
                  <button onClick={() => handleDelete(user.id)} className="text-red-600 hover:underline ml-2">删除</button>
                )}
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  )
}